package com.example.socialapp

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import androidx.navigation.NavType
import com.example.socialapp.ui.auth.forgotpassword.ForgotPasswordScreen
import com.example.socialapp.ui.auth.forgotpassword.ForgotPasswordViewModel
import com.example.socialapp.ui.auth.login.LoginScreen
import com.example.socialapp.ui.auth.login.LoginViewModel
import com.example.socialapp.ui.auth.register.RegisterScreen
import com.example.socialapp.ui.auth.register.RegisterViewModel
import com.example.socialapp.ui.auth.terms.TermsScreen
import com.example.socialapp.ui.main.MainScreen
import com.example.socialapp.ui.theme.SocialAppTheme
import com.example.socialapp.ui.settings.SettingsScreen
import com.example.socialapp.ui.chat.ChatDetailScreen
import com.example.socialapp.ui.notification.NotificationScreen
import com.example.socialapp.ui.post.CreatePostScreen
import com.example.socialapp.ui.post.PostDetailScreen
import com.example.socialapp.ui.profile.UserProfileScreen
import com.example.socialapp.ui.search.SearchScreen
import com.example.socialapp.ui.stats.UserStatsScreen
import com.example.socialapp.ui.topic.TopicDetailScreen
import com.example.socialapp.ui.bookmark.BookmarkScreen
import com.example.socialapp.ui.main.screens.ChatScreen
import com.example.socialapp.ui.theme.ThemeCustomizationScreen
import com.example.socialapp.ui.recommendation.RecommendationScreen
import com.example.socialapp.ui.social.SocialGraphScreen
import dagger.hilt.android.AndroidEntryPoint
import timber.log.Timber

/**
 * 应用的主入口Activity
 */
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            SocialAppTheme {
                // 使用主题背景颜色的Surface容器
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    val navController = rememberNavController()
                    val navBackStackEntry by navController.currentBackStackEntryAsState()
                    val currentRoute = navBackStackEntry?.destination?.route
                    
                    Scaffold { innerPadding ->
                        NavHost(
                            navController = navController,
                            startDestination = Screen.Login.route,
                            modifier = Modifier.padding(innerPadding)
                        ) {
                            // 登录界面
                            composable(Screen.Login.route) {
                                val viewModel = hiltViewModel<LoginViewModel>()
                                LoginScreen(
                                    viewModel = viewModel,
                                    onNavigateToMain = {
                                        // 登录成功后导航到主界面并清除回退栈
                                        navController.navigate(Screen.Main.route) {
                                            popUpTo(Screen.Login.route) { inclusive = true }
                                        }
                                    },
                                    onNavigateToRegister = {
                                        // 导航到注册界面
                                        navController.navigate(Screen.Register.route)
                                    },
                                    onNavigateToForgotPassword = {
                                        // 导航到忘记密码界面
                                        navController.navigate(Screen.ForgotPassword.route)
                                    },
                                    onGoogleSignIn = {
                                        Timber.d("谷歌登录")
                                        // 实现谷歌登录
                                    },
                                    onFacebookSignIn = {
                                        Timber.d("脸书登录")
                                        // 实现脸书登录
                                    },
                                    onAppleSignIn = {
                                        Timber.d("苹果登录")
                                        // 实现苹果登录
                                    }
                                )
                            }
                            
                            // 注册界面
                            composable(Screen.Register.route) {
                                val viewModel = hiltViewModel<RegisterViewModel>()
                                RegisterScreen(
                                    viewModel = viewModel,
                                    onNavigateToMain = {
                                        // 注册成功后导航到主界面并清除回退栈
                                        navController.navigate(Screen.Main.route) {
                                            popUpTo(Screen.Login.route) { inclusive = true }
                                        }
                                    },
                                    onNavigateToLogin = {
                                        // 返回登录界面
                                        navController.navigateUp()
                                    },
                                    onNavigateToTerms = {
                                        // 导航到条款界面
                                        navController.navigate("${Screen.Terms.route}?showPrivacyPolicy=false")
                                    },
                                    onGoogleSignIn = {
                                        Timber.d("谷歌注册")
                                        // 实现谷歌注册
                                    },
                                    onFacebookSignIn = {
                                        Timber.d("脸书注册")
                                        // 实现脸书注册
                                    },
                                    onAppleSignIn = {
                                        Timber.d("苹果注册")
                                        // 实现苹果注册
                                    }
                                )
                            }
                            
                            // 忘记密码界面
                            composable(Screen.ForgotPassword.route) {
                                val viewModel = hiltViewModel<ForgotPasswordViewModel>()
                                ForgotPasswordScreen(
                                    viewModel = viewModel,
                                    onNavigateToLogin = {
                                        // 返回登录界面
                                        navController.navigateUp()
                                    }
                                )
                            }
                            
                            // 条款界面 - 接受可选参数以确定显示哪种条款
                            composable(
                                route = "${Screen.Terms.route}?showPrivacyPolicy={showPrivacyPolicy}",
                                arguments = listOf(
                                    navArgument("showPrivacyPolicy") {
                                        defaultValue = "false"
                                        nullable = true
                                    }
                                )
                            ) { backStackEntry ->
                                val showPrivacyPolicy = backStackEntry.arguments?.getString("showPrivacyPolicy")?.toBoolean() ?: false
                                TermsScreen(
                                    onNavigateBack = {
                                        navController.navigateUp()
                                    },
                                    showPrivacyPolicy = showPrivacyPolicy
                                )
                            }
                            
                            // 主界面（含底部导航栏）
                            composable(Screen.Main.route) {
                                MainScreen(
                                    onLogout = {
                                        // 退出登录
                                        navController.navigate(Screen.Login.route) {
                                            popUpTo(Screen.Main.route) { inclusive = true }
                                        }
                                    },
                                    onNavigateToSettings = {
                                        // 前往设置界面
                                        navController.navigate(Screen.Settings.route)
                                    },
                                    onNavigateToCreatePost = {
                                        // 前往创建动态界面
                                        navController.navigate(Screen.CreatePost.route)
                                    },
                                    onNavigateToSearch = {
                                        // 前往搜索界面
                                        navController.navigate(Screen.Search.route)
                                    },
                                    onNavigateToPostDetail = { postId ->
                                        // 前往动态详情界面
                                        navController.navigate("${Screen.PostDetail.route}/$postId")
                                    },
                                    onNavigateToUserProfile = { userId ->
                                        // 前往用户资料界面
                                        navController.navigate("${Screen.UserProfile.route}/$userId")
                                    },
                                    onNavigateToChat = { userId, userName ->
                                        // 前往聊天详情界面
                                        navController.navigate("${Screen.ChatDetail.route}/$userId/$userName")
                                    },
                                    onNavigateToNotification = {
                                        // 前往通知界面
                                        navController.navigate(Screen.Notification.route)
                                    },
                                    onNavigateToBookmark = {
                                        // 前往收藏界面
                                        navController.navigate(Screen.Bookmark.route)
                                    },
                                    onNavigateToRecommendation = {
                                        // 前往内容推荐界面
                                        navController.navigate(Screen.Recommendation.route)
                                    }
                                )
                            }
                            
                            // 设置界面
                            composable(Screen.Settings.route) {
                                SettingsScreen(
                                    onNavigateBack = {
                                        navController.navigateUp()
                                    },
                                    onNavigateToAccountSettings = {
                                        // TODO: 导航到账户设置详情界面
                                    },
                                    onNavigateToPrivacySettings = {
                                        // TODO: 导航到隐私设置详情界面
                                    },
                                    onNavigateToNotificationSettings = {
                                        // TODO: 导航到通知设置详情界面
                                    },
                                    onNavigateToThemeCustomization = {
                                        // 导航到主题自定义界面
                                        navController.navigate(Screen.ThemeCustomization.route)
                                    }
                                )
                            }
                            
                            // 聊天界面
                            composable(Screen.Chat.route) {
                                ChatScreen(
                                    onNavigateToChatDetail = { chatId, chatName ->
                                        navController.navigate("${Screen.ChatDetail.route}/$chatId/$chatName")
                                    }
                                )
                            }
                            
                            // 聊天详情界面
                            composable(
                                route = "${Screen.ChatDetail.route}/{chatId}/{chatName}",
                                arguments = listOf(
                                    navArgument("chatId") { type = NavType.StringType },
                                    navArgument("chatName") { type = NavType.StringType }
                                )
                            ) { backStackEntry ->
                                val chatId = backStackEntry.arguments?.getString("chatId") ?: ""
                                val chatName = backStackEntry.arguments?.getString("chatName") ?: ""
                                
                                ChatDetailScreen(
                                    chatId = chatId,
                                    chatName = chatName,
                                    onNavigateBack = {
                                        navController.navigateUp()
                                    }
                                )
                            }
                            
                            // 创建动态界面
                            composable(Screen.CreatePost.route) {
                                CreatePostScreen(
                                    onNavigateBack = {
                                        navController.navigateUp()
                                    },
                                    onPostSuccess = {
                                        // 发布成功后返回主界面
                                        navController.navigateUp()
                                        // TODO: 可以显示Toast或Snackbar提示发布成功
                                    }
                                )
                            }

                            // 动态详情
                            composable(
                                route = "${Screen.PostDetail.route}/{postId}",
                                arguments = listOf(
                                    navArgument("postId") { type = NavType.StringType }
                                )
                            ) { backStackEntry ->
                                val postId = backStackEntry.arguments?.getString("postId") ?: ""
                                PostDetailScreen(
                                    postId = postId,
                                    onNavigateBack = { navController.popBackStack() },
                                    onNavigateToUserProfile = { userId ->
                                        navController.navigate("${Screen.UserProfile.route}/$userId")
                                    }
                                )
                            }

                            // 用户资料界面
                            composable(
                                route = "${Screen.UserProfile.route}/{userId}",
                                arguments = listOf(
                                    navArgument("userId") { 
                                        type = NavType.StringType
                                        defaultValue = ""
                                    }
                                )
                            ) { backStackEntry ->
                                val userId = backStackEntry.arguments?.getString("userId") ?: ""
                                UserProfileScreen(
                                    userId = userId,
                                    onNavigateBack = { navController.popBackStack() },
                                    onNavigateToChat = { chatUserId ->
                                        navController.navigate("${Screen.ChatDetail.route}/$chatUserId/$userId")
                                    },
                                    onNavigateToPostDetail = { postId ->
                                        navController.navigate("${Screen.PostDetail.route}/$postId")
                                    },
                                    onNavigateToUserStats = { statUserId ->
                                        navController.navigate("${Screen.UserStats.route}/$statUserId")
                                    },
                                    onNavigateToSocialGraph = { graphUserId ->
                                        navController.navigate("${Screen.SocialGraph.route}/$graphUserId")
                                    }
                                )
                            }

                            // 搜索界面
                            composable(route = Screen.Search.route) {
                                SearchScreen(
                                    onNavigateBack = { navController.popBackStack() },
                                    onNavigateToUserProfile = { userId ->
                                        navController.navigate("${Screen.UserProfile.route}/$userId")
                                    },
                                    onNavigateToPostDetail = { postId ->
                                        navController.navigate("${Screen.PostDetail.route}/$postId")
                                    },
                                    onNavigateToTopic = { topicId ->
                                        // 导航到话题详情页
                                        navController.navigate("${Screen.TopicDetail.route}/$topicId")
                                    }
                                )
                            }
                            
                            // 通知界面
                            composable(route = Screen.Notification.route) {
                                NotificationScreen(
                                    onNavigateBack = { navController.popBackStack() },
                                    onNavigateToUserProfile = { userId ->
                                        navController.navigate("${Screen.UserProfile.route}/$userId")
                                    },
                                    onNavigateToPostDetail = { postId ->
                                        navController.navigate("${Screen.PostDetail.route}/$postId")
                                    },
                                    onNavigateToSettings = {
                                        navController.navigate(Screen.Settings.route)
                                    }
                                )
                            }
                            
                            // 话题详情界面
                            composable(
                                route = "${Screen.TopicDetail.route}/{topicId}",
                                arguments = listOf(
                                    navArgument("topicId") { type = NavType.StringType }
                                )
                            ) { backStackEntry ->
                                val topicId = backStackEntry.arguments?.getString("topicId") ?: ""
                                TopicDetailScreen(
                                    topicId = topicId,
                                    onNavigateBack = { navController.popBackStack() },
                                    onNavigateToUserProfile = { userId ->
                                        navController.navigate("${Screen.UserProfile.route}/$userId")
                                    },
                                    onNavigateToPostDetail = { postId ->
                                        navController.navigate("${Screen.PostDetail.route}/$postId")
                                    }
                                )
                            }
                            
                            // 书签/收藏界面
                            composable(route = Screen.Bookmark.route) {
                                BookmarkScreen(
                                    onNavigateBack = { navController.popBackStack() },
                                    onNavigateToUserProfile = { userId ->
                                        navController.navigate("${Screen.UserProfile.route}/$userId")
                                    },
                                    onNavigateToPostDetail = { postId ->
                                        navController.navigate("${Screen.PostDetail.route}/$postId")
                                    },
                                    onNavigateToSearch = {
                                        navController.navigate(Screen.Search.route)
                                    }
                                )
                            }
                            
                            // 主题自定义界面
                            composable(route = Screen.ThemeCustomization.route) {
                                ThemeCustomizationScreen(
                                    onNavigateBack = { navController.popBackStack() },
                                    onApplyTheme = { themeSettings ->
                                        // TODO: 应用主题设置逻辑，使用ViewModel或DataStore保存
                                        Timber.d("应用主题设置: $themeSettings")
                                    }
                                )
                            }
                            
                            // 用户活跃度统计界面
                            composable(
                                route = "${Screen.UserStats.route}/{userId}",
                                arguments = listOf(
                                    navArgument("userId") { 
                                        type = NavType.StringType
                                        defaultValue = ""
                                    }
                                )
                            ) { backStackEntry ->
                                val userId = backStackEntry.arguments?.getString("userId") ?: ""
                                UserStatsScreen(
                                    userId = userId,
                                    onNavigateBack = { navController.popBackStack() },
                                    onShare = {
                                        // 分享统计数据
                                        Timber.d("分享用户活跃度统计")
                                    }
                                )
                            }

                            // 内容推荐界面
                            composable(route = Screen.Recommendation.route) {
                                RecommendationScreen(
                                    onNavigateBack = { navController.popBackStack() },
                                    onNavigateToUserProfile = { userId ->
                                        navController.navigate("${Screen.UserProfile.route}/$userId")
                                    },
                                    onNavigateToPostDetail = { postId ->
                                        navController.navigate("${Screen.PostDetail.route}/$postId")
                                    },
                                    onNavigateToTopic = { topicId ->
                                        navController.navigate("${Screen.TopicDetail.route}/$topicId")
                                    }
                                )
                            }
                            
                            // 社交关系图界面
                            composable(
                                route = "${Screen.SocialGraph.route}/{userId}",
                                arguments = listOf(
                                    navArgument("userId") { 
                                        type = NavType.StringType
                                        defaultValue = ""
                                    }
                                )
                            ) { backStackEntry ->
                                val userId = backStackEntry.arguments?.getString("userId") ?: ""
                                SocialGraphScreen(
                                    userId = userId,
                                    onNavigateBack = { navController.popBackStack() },
                                    onNavigateToUserProfile = { profileUserId ->
                                        navController.navigate("${Screen.UserProfile.route}/$profileUserId")
                                    }
                                )
                            }
                        }
                    }
                }
            }
        }
    }
}